import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { LoginParams, LoginResult } from '@/types/auth'
import { userApi } from '@/api/modules/user'
import {useRouter} from "vue-router";

export const useUserStore = defineStore('user', () => {
  // 从 localStorage 初始化 token
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<LoginResult['userInfo'] | null>(null)
  const router = useRouter()
  // 登录
  const login = async (params: LoginParams) => {
    try {
      // 1. 登录获取 token
      const newToken = await userApi.login(params)
      
      // 2. 先存储 token，这样后续请求可以带上 token
      localStorage.setItem('token', newToken)
      token.value = newToken

      // 3. 获取完整的用户信息
      await getUserInfo()
    } catch (error) {
      console.log('error', error)
      logout()
      throw error
    }
  }
  
  // 获取用户信息
  const getUserInfo = async () => {
    const info = await userApi.getUserInfo()
    console.log('info111', info)
    userInfo.value = info
    // 存储到 userInfo
    localStorage.setItem('userInfo', JSON.stringify(info))
    return info
  }
  
  // 退出登录
  const logout = () => {
    // 清理本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    // 跳转至 登录页
    router.push('/login')
    // 重置状态
    token.value = ''
    userInfo.value = null
  }
  
  // 更新个人信息
  const updateCurrentUser = async (data: UpdateUserDTO) => {
    await userApi.updateCurrentUser(data)
    // 更新成功后重新获取用户信息
    await getUserInfo()
  }
  
  return {
    token,
    userInfo,
    login,
    getUserInfo,
    logout,
    updateCurrentUser
  }
}) 